/**
 * API工具类 - 处理与后端的所有API交互
 * 突袭简历 - AI智能简历优化平台
 */

class ApiClient {
    constructor() {
        this.baseURL = 'http://localhost:8080';
        this.token = localStorage.getItem('auth_token');
        this.uid = localStorage.getItem('uid');
    }

    // 设置认证信息
    setAuth(token, uid) {
        this.token = token;
        this.uid = uid;
        localStorage.setItem('auth_token', token);
        localStorage.setItem('uid', uid);
    }

    // 清除认证信息
    clearAuth() {
        this.token = null;
        this.uid = null;
        localStorage.removeItem('auth_token');
        localStorage.removeItem('uid');
    }

    // 通用请求方法
    async request(endpoint, options = {}) {
        const url = `${this.baseURL}${endpoint}`;
        const headers = {
            'Content-Type': 'application/json',
            ...options.headers
        };

        // 添加认证头
        if (this.uid) {
            headers['uid'] = this.uid;
        }
        if (this.token) {
            headers['Authorization'] = `Bearer ${this.token}`;
        }

        try {
            const response = await fetch(url, {
                ...options,
                headers
            });

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
                return await response.json();
            }
            return await response.text();
        } catch (error) {
            console.error('API请求失败:', error);
            throw error;
        }
    }

    // GET请求
    async get(endpoint, params = {}) {
        const url = new URL(`${this.baseURL}${endpoint}`);
        Object.keys(params).forEach(key => {
            if (params[key] !== undefined && params[key] !== null) {
                url.searchParams.append(key, params[key]);
            }
        });
        
        return this.request(url.pathname + url.search, {
            method: 'GET'
        });
    }

    // POST请求
    async post(endpoint, data = {}) {
        return this.request(endpoint, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    }

    // POST表单请求
    async postForm(endpoint, formData) {
        const headers = {};
        if (this.uid) {
            headers['uid'] = this.uid;
        }
        if (this.token) {
            headers['Authorization'] = `Bearer ${this.token}`;
        }

        return this.request(endpoint, {
            method: 'POST',
            headers,
            body: formData
        });
    }

    // 用户相关API
    async getUserInfo() {
        return this.get('/v1/user/info');
    }

    async updateNickname(nickname) {
        const formData = new FormData();
        formData.append('nickname', nickname);
        return this.postForm('/v1/user/nickname/update', formData);
    }

    async bindTelephone(telephone, smsCode) {
        const formData = new FormData();
        formData.append('telephone', telephone);
        formData.append('sms_code', smsCode);
        return this.postForm('/v1/user/telephone/bind', formData);
    }

    // 简历相关API
    async getMyResumes(pageNo = 1, pageSize = 10) {
        return this.get('/v1/resume/list/mine', {
            page_no: pageNo,
            page_size: pageSize
        });
    }

    async getResumeDetail(resumeId) {
        return this.get('/v1/resume/detail', {
            resume_id: resumeId
        });
    }

    async deleteResume(resumeId) {
        const formData = new FormData();
        formData.append('resume_id', resumeId);
        return this.postForm('/v1/resume/delete', formData);
    }

    // 简历模板相关API
    async getResumeTemplates(pageNo = 1, pageSize = 20) {
        return this.get('/v1/resume/template/list', {
            page_no: pageNo,
            page_size: pageSize
        });
    }

    async getTemplateDetail(templateId) {
        return this.get('/v1/resume/template/detail', {
            template_id: templateId
        });
    }

    // 登录相关API
    async login(telephone, password) {
        const formData = new FormData();
        formData.append('telephone', telephone);
        formData.append('password', password);
        return this.postForm('/v1/login', formData);
    }

    async register(telephone, password, smsCode, nickname = '') {
        const formData = new FormData();
        formData.append('telephone', telephone);
        formData.append('password', password);
        formData.append('sms_code', smsCode);
        if (nickname) {
            formData.append('nickname', nickname);
        }
        return this.postForm('/v1/register', formData);
    }

    // 短信相关API
    async sendSmsCode(telephone, captchaId, captchaCode) {
        const formData = new FormData();
        formData.append('telephone', telephone);
        formData.append('captcha_id', captchaId);
        formData.append('captcha_code', captchaCode);
        return this.postForm('/v1/sms/send', formData);
    }

    // 验证码相关API
    async getCaptcha() {
        return this.get('/v1/captcha');
    }
}

// 创建全局API客户端实例
window.apiClient = new ApiClient();

// 导出API客户端
if (typeof module !== 'undefined' && module.exports) {
    module.exports = ApiClient;
}